/**
 * @author Linrui
 * @since 2011-04-29
 * 首页主要类别拦截器，检测首页的类别数据是否加载
 */
package com.qeado.util.interceptors;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.qeado.sort.model.Sort;
import com.qeado.sort.service.SortService;

@Component
public class SubSortInterceptor extends AbstractInterceptor {
	@Autowired
	private SortService sortService;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {

		List<Sort> mainSort = (List<Sort>) ActionContext.getContext()
				.getSession().get("indexMainMenu");
		Map<String, List<Sort>> subSortList_1;
		Map<String, List<Sort>> subSortList_2;
		/**
		 * for every main sort , if they are not load into the index page , they
		 * will be load in the indexInterceptor .
		 */
		if (ActionContext.getContext().getSession().get("subSortList_1") == null) {
			mainSort = (List<Sort>) ActionContext.getContext().getSession()
					.get("indexMainMenu");
			subSortList_1 = new HashMap<String, List<Sort>>();
			subSortList_2 = new HashMap<String, List<Sort>>();
			/* 对于每个1级子类，查询它的2级子类 */
			for (Iterator iterator = mainSort.iterator(); iterator.hasNext();) {
				Sort sort = (Sort) iterator.next();
				//System.out.println("1:" + sort.getTypeName());
				List<Sort> list = sortService.listByPid(sort.getId());
				subSortList_1.put(sort.getTypeCode(), list);
				/* 对于每个2级子类，查询它的3级子类 */
				for (Iterator iterator_2 = list.iterator(); iterator_2
						.hasNext();) {
					Sort sort_2 = (Sort) iterator_2.next();
					//System.out.println("2:" + sort_2.getTypeName());
					List<Sort> list_2 = sortService.listByPid(sort_2.getId());
					subSortList_2.put(sort_2.getTypeCode(), list_2);
				}
			}
			ActionContext.getContext().getSession().put("subSortList_1",
					subSortList_1);
			ActionContext.getContext().getSession().put("subSortList_2",
					subSortList_2);
		}
		return invocation.invoke();
	}

}
